package cn.lili.modules.member.serviceimpl;

import cn.lili.cache.LockPrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.aop.annotation.RedPackLogPoint;
import cn.lili.modules.member.entity.dos.RedPackTask;
import cn.lili.modules.member.entity.dos.RedPackUser;
import cn.lili.modules.member.mapper.RedPackUserMapper;
import cn.lili.modules.member.service.RedPackUserService;
import cn.lili.modules.payment.entity.dto.UserRedPackUpdateDTO;
import cn.lili.mybatis.util.PageUtil;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojos.OpenAppUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
@Slf4j
public class RedPackUserServiceImpl extends ServiceImpl<RedPackUserMapper, RedPackUser>
        implements RedPackUserService {

    private final RedissonClient redisson;

    private final UserApi userApi;

    /**
     * 获取用户和用户红包数据
     * @param sessionId
     * @return
     * @throws ParseException
     */
    @Override
    public RedPackUser getUserInfo (String sessionId) throws ParseException {
        RLock rLock = redisson.getLock("getUserInfo_" + UserContext.getCurrentId());
        try {
            rLock.lock();
            OpenAppUser openAppUser = userApi.getUserinfo(sessionId);
            if (null == openAppUser) {
                throw new ServiceException("用户信息获取失败");
            }
            log.info("红包广场用户信息：{}", openAppUser.getOpenId());
            boolean authenticationFlag = userApi.isAuthentication(openAppUser.getUId());
            RedPackUser redPackUser = getUserInfoByOpenId(openAppUser.getOpenId());
            //RedPackUser redPackUser = getRedPackUser(UserContext.getCurrentId());
            if (null == redPackUser) {
                redPackUser = new RedPackUser();
                redPackUser.setUserId(UserContext.getCurrentId());
                redPackUser.setOpenId(openAppUser.getOpenId());
                redPackUser.setUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername());
                redPackUser.setStatus(1);
                redPackUser.setRedPackCount(0);
                redPackUser.setFyUserId(openAppUser.getUId());
                isVip(openAppUser, redPackUser);
                if (authenticationFlag) {
                    redPackUser.setIsCertification(1);
                }else {
                    redPackUser.setIsCertification(0);
                }
                this.save(redPackUser);
            }else {
                if (StringUtils.isEmpty(redPackUser.getFyUserId())) {
                    redPackUser.setFyUserId(openAppUser.getUId());
                }
                if (authenticationFlag) {
                    redPackUser.setIsCertification(1);
                }else {
                    redPackUser.setIsCertification(0);
                }
                isVip(openAppUser, redPackUser);
                this.updateById(redPackUser);
            }
            log.info("红包广场用户信息END");
            return redPackUser;
        }catch (Exception e) {
            throw e;
        }finally {
            rLock.unlock();
        }
    }

    private void isVip(OpenAppUser openAppUser, RedPackUser redPackUser) throws ParseException {
        log.info("是否会员用户：{},{},{}", openAppUser.getVip(),openAppUser.getIs_vip(), openAppUser.getVip_time());
        if (StringUtils.isEmpty(openAppUser.getVip()) || "0".equals(openAppUser.getVip())) {
            redPackUser.setIsVip(0);
        }else {
            if (StringUtils.isEmpty(openAppUser.getVip_time())) {
                redPackUser.setIsVip(0);
            }else {
                try {
                    /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date vipTime = sdf.parse(openAppUser.getVip_time());*/
                    Date vipTime = new Date(Long.parseLong(openAppUser.getVip_time()) * 1000);
                    if (vipTime.before(new Date())) {
                        redPackUser.setIsVip(0);
                    }else {
                        redPackUser.setIsVip(1);
                    }
                }catch (Exception e) {
                    redPackUser.setIsVip(0);
                }

            }
        }
    }

    /**
     * 根据openID获取红包用户信息
     * @param openId
     * @return
     */
    public RedPackUser getUserInfoByOpenId (String openId) {
        LambdaQueryWrapper<RedPackUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RedPackUser::getOpenId, openId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }


    /**
     * 根据用户id获取用户红包数量
     * @param userId
     * @return
     */
    @Override
    public RedPackUser getRedPackUser (String userId) {
        LambdaQueryWrapper<RedPackUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RedPackUser::getUserId, userId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    /**
     * 用户红包变动记录
     * @param userRedPackUpdateDTO
     */
    @Override
    @RedPackLogPoint
    @Transactional
    public void updateMemberRedPack(UserRedPackUpdateDTO userRedPackUpdateDTO) {

        RLock lock = null;
        try {
            lock = redisson.getLock(LockPrefix.RED_PACK.getPrefix() + userRedPackUpdateDTO.getUserId());
            lock.lock();
            //获取当前会员信息
            RedPackUser redPackUser = getRedPackUser(userRedPackUpdateDTO.getUserId());
            if (redPackUser != null) {
                //如果增加红包
                if (Boolean.TRUE.equals(userRedPackUpdateDTO.getUserRedPackServiceEnum().getAdd())) {
                    redPackUser.setRedPackCount(redPackUser.getRedPackCount() + userRedPackUpdateDTO.getRedPack());
                    redPackUser.setLastTaskTime(new Date());
                    this.updateById(redPackUser);
                }
                //否则扣除红包
                else {
                    redPackUser.setRedPackCount(redPackUser.getRedPackCount() - userRedPackUpdateDTO.getRedPack());
                    this.updateById(redPackUser);
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (lock != null) lock.unlock();
        }
    }

    /**
     * 分页获取红包用户列表
     * @param redPackUser
     * @param pageVO
     * @return
     */
    @Override
    public Page<RedPackUser> getByPage (RedPackUser redPackUser, PageVO pageVO) {
        LambdaQueryWrapper<RedPackUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(redPackUser.getUserName()), RedPackUser::getUserName, redPackUser.getUserName());
        queryWrapper.eq(null != redPackUser.getIsCertification(), RedPackUser::getIsCertification, redPackUser.getIsCertification());
        queryWrapper.eq(null != redPackUser.getIsVip(), RedPackUser::getIsVip, redPackUser.getIsVip());
        queryWrapper.eq(null != redPackUser.getStatus(), RedPackUser::getStatus, redPackUser.getStatus());
        queryWrapper.orderByDesc(RedPackUser::getLastTaskTime);
        return this.baseMapper.selectPage(PageUtil.initPage(pageVO), queryWrapper);
    }

    /**
     * 修改用户状态
     * @param id
     * @param status
     */
    @Override
    public void updateUserStatus (String id, Integer status) {
        if (StringUtils.isEmpty(id) || null == status) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        RedPackUser redPackUser = this.getById(id);
        if (null == redPackUser) {
            throw new ServiceException("用户不存在");
        }

        redPackUser.setStatus(status);
        this.updateById(redPackUser);
    }

    /**
     * 是否实名认证
     * @return
     */
    @Override
    public Integer getIsCertification () {
        RedPackUser redPackUser = this.getRedPackUser(UserContext.getCurrentId());
        if (null == redPackUser) {
            throw new ServiceException("用户不存在");
        }
        boolean authenticationFlag = userApi.isAuthentication(redPackUser.getFyUserId());
        return authenticationFlag ? 1 : 0;
    }

    /**
     * 获取超过配置天数没有做任务的用户
     * @return
     */
    @Override
    public List<RedPackUser> getListByLastTime () {
        return this.baseMapper.getListByLastTime(7);
    }
}
